import React, { Component } from 'react';
import { Button, Tooltip, Spin, message } from 'antd';
import { WeaInputSearch, WeaAlertPage, WeaNewScroll, WeaErrorPage, WeaTab, WeaDateSwitch, WeaPopoverHrm, WeaDragChoose, WeaLocaleProvider } from 'ecCom';
import { WeaTableNew } from 'comsMobx';
import * as CarUtil from '../../util/CarUtil';

const WeaTable = WeaTableNew.WeaTable;

import Apis from '../../apis/car';
import moment from 'moment';
import { inject, observer } from 'mobx-react';
import CarViewDialog from '../car/dialog/CarViewDialog';
import CreateCarFlowDialog from '../car/dialog/CreateCarFlowDialog';

const getLabel = WeaLocaleProvider.getLabel;
let carCondition = {
  carNo: '',
  currentdate: '',
  bywhat: '',
  subId: '',
  subName: '',
  carId: '',
};
let carFlowData = {};
import '../../lib/wdCalendar_lang_wev8';

const i18n = window.meetingCalendarI18n;
@inject('carUseContainerStore')
@observer
class CarUseContainer extends Component {
  constructor(props) {
    super(props);
    carCondition = {
      carNo: '',
      currentdate: '',
      bywhat: '',
      subId: '',
      subName: '',
      carId: '',
    };
    this.searchByCarNo = this.searchByCarNo.bind(this);
    this.query = this.query.bind(this);
    this.state = {
      timeType: 'day',
      date: new Date(),
      subId: props.subId,
      subName: props.subName,
      color: {},
      baseLoading: true,
      cars: [],
      useMap: {}, // key为carid，value为使用信息
      startHour: 0,
      endHour: 23,
      duration: 0,
      carNo: '', // 搜索栏
      carLoading: true,
      pageTabKey: '',
      carId: '',
      createObj: {},
      createVisible: false,
      previewMeetingId: '',
      roomPlanVisible: false,
      conHeight: 0,
      tabHeight: 0,
      listHeight: 0,
      dialogZIndex: 801,
      callback: undefined,
    };
  }

  componentDidMount() {
    Apis.getCarReportBaseData().then((result) => {
      let { agreementColor, conflictedColor, usedColor, subname, timestart, timeend, roomConflictType } = result;
      agreementColor || (agreementColor = '#FFE4C4'), conflictedColor || (conflictedColor = '#FBDFEB'), usedColor || (usedColor = '#E3F6D8');
      this.setState({
        subName: subname,
        color: { agreementColor, conflictedColor, usedColor },
        baseLoading: false,
        startHour: timestart,
        endHour: timeend,
        roomConflictType,
      });
    });


    const { carUseContainerStore } = this.props;
    carUseContainerStore.doTableLoading(); // 初始化列表
    carUseContainerStore.initConditionDatas(); // 初始化高级搜索区域
    this.query();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.subId != this.props.subId) {
      carCondition.subId = nextProps.subId;
      carCondition.subName = nextProps.subName;
      this.setState({
        subId: nextProps.subId,
        subName: nextProps.subName,
      }, this.query);
    }
    if (this.state.dialogZIndex != nextProps.dialogZIndex && nextProps.dialogZIndex) {
      this.setState({
        dialogZIndex: nextProps.dialogZIndex,
      });
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // 处理高度自适应问题
    let container = jQuery('.car-container', ReactDOM.findDOMNode(this)),
      conHeight = this.props.height ? (this.props.height - 108) : container.height();
    let tab = jQuery('.car-tab', container),
      tabHeight = tab.height();
    if (tabHeight <= 0) {
      tabHeight = this.state.tabHeight;
    }
    let listHeight;
    if (tabHeight > (conHeight * 0.55)) {
      listHeight = (conHeight * 0.45);
      tabHeight = (conHeight * 0.55);
    } else {
      listHeight = conHeight - tabHeight;
    }
    if (conHeight !== this.state.conHeight || tabHeight !== this.state.tabHeight || listHeight !== this.state.listHeight) {
      this.setState({
        conHeight,
        tabHeight,
        listHeight,
      });
    }
  }

  /* 周月日组件切换回调 */
  onChangeWeaDateSwitch = (type, date, range) => {
    if (type != this.state.timeType) { // 类型切换
      const bywhat = type == 'day' ? 4 : type == 'week' ? 3 : 2;
      carCondition.bywhat = bywhat;
      carCondition.carId = '';
      this.setState({ timeType: type, carId: '' }, this.query);
    }
    const dateClone = moment(date);// 克隆date
    const stateDate = moment.isMoment(this.state.date) ? this.state.date : moment(this.state.date);
    if (dateClone.format('YYYY-MM-DD') != stateDate.format('YYYY-MM-DD')) { // 日期切换
      const currentdate = dateClone.format('YYYY-MM-DD');
      carCondition.currentdate = currentdate;
      carCondition.carId = '';
      this.setState({ date: dateClone.toDate(), carId: '' }, this.query);
    }
  }

  searchByCarNo(value = this.state.carNo) {
    carCondition.carId = '';
    this.setState({
      carId: '',
      carNo: value,
    }, this.query(value));
  }

  /* 查询车辆使用情况与车辆列表 */
  query(value = this.state.carNo, carId = '', clearUserMap = true) {
    const { timeType } = this.state;
    const newState = {
      carNo: value,
    };
    this.setState(newState);
    carCondition.carNo = value;
    const params = this.getQueryParams(value);
    clearUserMap && (newState.useMap = {});
    const { carUseContainerStore } = this.props;
    Apis.getCarReportData(params).then(
      (result) => {
        const duration = (timeType == 'day' && result.dspUnit > 0) ? 60 / result.dspUnit : 0;
        const useMap = {};
        result.datas && result.datas.forEach((obj) => {
          if (!obj.carid) return;
          useMap[obj.carid] = obj.info;
        });
        this.setState({
          cars: result.cars || [],
          useMap,
          duration,
          carLoading: false,
        });
        if (this.state.callback) {
          this.state.callback(false);
        }
      },
    );
    if (carUseContainerStore.form && carUseContainerStore.form.fields.size > 0) {
      this.searchList();
    }
    // this.queryPageTable(params);
  }

  /* 根据state与传入的车辆名称生成查询用的参数，既可以给车辆使用情况用，也可以给车辆列表用 */
  getQueryParams(value = this.state.carNo) {
    return carCondition;
  }

  /* 查询车辆列表 */
  queryPageTable(params = {}) {
    const { carUseContainerStore } = this.props;
    carUseContainerStore.doTableLoading(params);
  }

  /* 根据carId查询车辆列表 */
  queryPageTableByCarId(carId) {
    if (carId != this.state.carId) {
      this.setState({
        carId,
      });
      carCondition.carId = carId;
    } else {
      this.setState({
        carId: '',
      });
      carCondition.carId = '';
    }

    this.query();
  }

  render() {
    const { carUseContainerStore } = this.props;
    const { loading, title, form, conditioninfo, topTab, selectedKey, showSearchAd, sessionkey, tableStore } = carUseContainerStore;
    // 上方使用的基础数据
    const { timeType, baseLoading, subName, color, date, previewMeetingId } = this.state;
    if (baseLoading) {
      return (
        <div className="align-center top40"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@0nmswq`} /></div>
      );
    }
    // 列表中使用的数据
    const { carLoading, startHour, endHour, cars, carId, roomPlanVisible } = this.state;
    // 下方列表的key
    const { pageTabKey } = this.state;
    // 新建车辆的控制
    const { createObj, createVisible } = this.state;

    const { blockNum, tableTitle, tableHeaders } = this.getTableHeaderInfo(timeType, date, startHour, endHour);

    const { canCreate } = this.props;
    // 车辆使用情况的内容
    const tableContent = (
      <table className="car-tab">
        <tbody>

          {!carLoading && (cars && cars.length > 0) &&
            cars.map((car, index) => {
              const tdList = this.createTdList(car, blockNum, index);
              const title = createRoomTitle(car.title);
              const tdClass = carId == car.id ? 'car-name cur' : 'car-name';
              return (
                <tr className={index == 0 ? 'no-border-top' : ''}>
                  <Tooltip
                    ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@zdekaw@${index}`}
                    title={title}
                    getTooltipContainer={() => container}
                    overlayClassName="white-tooltip"
                    placement="right"
                  >
                    <td className={tdClass} onClick={this.queryPageTableByCarId.bind(this, car.id)}>{car.name}</td>
                  </Tooltip>
                  {tdList}
                </tr>
              );
            })
          }
        </tbody>
      </table>
    );

    // 高度控制
    const { tabHeight, listHeight, conHeight, dialogZIndex } = this.state;
    let tabHeightValue = tabHeight,
      listHeightValue = listHeight;
    // if (tabHeight + listHeight <= (conHeight)) {
    //     tabHeightValue = "auto";
    //     listHeightValue = "auto";
    // } else if (tabHeight >= (conHeight) * 0.55 && listHeight >= (conHeight) * 0.45) {
    //     tabHeightValue = "55%";
    //     listHeightValue = "45%";
    // } else if (tabHeight > (conHeight) * 0.55 && listHeight <= (conHeight) * 0.45) {
    //     tabHeightValue = (conHeight) - listHeight;
    //     listHeightValue = "auto";
    // } else {
    //     tabHeightValue = "auto";
    //     listHeightValue = (conHeight) - tabHeight;
    // }
    return (
      <div className="wea-car-con f12">

        <div className="car-top">
          <div className="car-top-con line">
            <span style={{ paddingRight: '15px' }}>{subName}</span>
            <WeaDateSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaDateSwitch@zcq8s1`} onChange={this.onChangeWeaDateSwitch} currentDay={date} />
            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@malo9i`} placement="bottom" title={getLabel(354, '刷新')}>
              <span
                className="icon-coms-Refresh"
                style={{
                  cursor: 'pointer',
                  padding: '0 10px',
                  color: '#B2B2B2',
                  fontSize: '16px',
                  display: 'inline-block',
                  position: 'absolute',
                  top: '15px',
                }}
                onClick={() => { this.setState({ carLoading: true }, this.query); }}
              />
            </Tooltip>
            <div className="legend">
              <div><div className="square" style={{ backgroundColor: color.usedColor }} /><span>{getLabel(19097, '占用')}</span></div>
              <div><div className="square" style={{ backgroundColor: color.conflictedColor }} /><span>{getLabel(386006, '冲突')}</span></div>
            </div>
          </div>
          {/* 车辆使用情况的头部 */}
          <table className="car-tab-header">
            <tbody>
              <tr className="no-border-top">
                <th className="first align-center">{getLabel(920, '车辆')}</th>
                <th colSpan={blockNum}>{tableTitle || `${getLabel(383375, '读取中')}...`}</th>
              </tr>
              {tableHeaders && tableHeaders.length > 0 && (
                <tr>
                  <th className="search"><WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@aqgzdu`} placeholder={getLabel(82291, '搜索车辆')} onSearch={this.searchByCarNo} value={this.state.carNo} /></th>
                  {tableHeaders.map(header => (<th className="header">{timeType && timeType == 'month' ? header + 1 : header}</th>))}
                </tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="car-container">
          {carLoading && <div className="align-center top40"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@d4f9w8`} /></div>}
          {!carLoading && (!cars || cars.length == 0) && (
            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@oeh8tj`} icon="icon-coms-Journal">
              <div>暂无车辆</div>
            </WeaAlertPage>
          )}
          <div className="tab-container" style={{ height: tabHeightValue }}>
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@1chpbo`} height="100%" ref="tabScroll">
              {/* 车辆使用情况的内容 */}
              {timeType == 'day' ? (
                <WeaDragChoose
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaDragChoose@i2gjrn`}
                  ref="drag"
                  activeStyle={{ backgroundColor: '#E1ECFF' }}
                  onSelectEnd={this.dragChooseEnd}
                  checkActive={this.checkDragActive}
                >
                  {tableContent}
                </WeaDragChoose>
              ) : tableContent}
            </WeaNewScroll>
            <CreateCarFlowDialog ecId={`${this && this.props && this.props.ecId || ''}_CreateCarFlowDialog@8k8k0a`} ref="createCarFlow" />
          </div>
          <div className="list-container carview-report" style={{ height: listHeightValue }}>
            {/* 车辆列表 */}
            {cars && cars.length > 0 &&
              (
                <div className="list-container list-report">
                  <div style={{ display: 'none' }}>
                    <WeaTab
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@em3yt9`}
                      datas={topTab}
                      keyParam="groupid"
                      searchType={['base', 'advanced']}
                      searchsBaseValue={this.getSearchBaseValue}
                      setShowSearchAd={this.setShowSearchAd}
                      showSearchAd={showSearchAd}
                      hideSearchAd={this.hideSearchAd}
                      searchsAd={CarUtil.getSearchs(form, conditioninfo)}
                      buttonsAd={this.getTabButtonsAd()}
                      onSearch={carUseContainerStore.doTableLoading}
                      onSearchChange={this.onSearchChange}
                    />
                  </div>
                  <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@frgd0e`} />
                  <WeaTable
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@gtv139`}
                    loading={loading}
                    sessionkey={pageTabKey}
                    comsWeaTableStore={tableStore}
                    hasOrder
                    needScroll={listHeightValue != 'auto'}
                    getColumns={this.getNewColumns}
                    onOperatesClick={this.onOperatesClick}
                  />
                </div>
              )
            }
          </div>
        </div>
        <CarViewDialog ecId={`${this && this.props && this.props.ecId || ''}_CarViewDialog@bstjpf`} ref="carview" />
      </div>
    );
  }

  getSearchBaseValue = () => {
    const { carUseContainerStore } = this.props;
    const { form } = carUseContainerStore;
    return form.isFormInit && form.getFormParams() && form.getFormParams().carNo || ''
  }

  setShowSearchAd = (bool) => {
    const { carUseContainerStore } = this.props;
    carUseContainerStore.setShowSearchAd(bool);
  }

  onSearchChange = (v) => {
    const { carUseContainerStore } = this.props;
    carUseContainerStore.appendFormFields({ carNo: v });
  }

  hideSearchAd = () => {
    const { carUseContainerStore } = this.props;
    carUseContainerStore.setShowSearchAd(false);
  }

  doCancel(id, tablename, cancelname) {
    const { carUseContainerStore } = this.props;
    const parm = { id, tablename, cancelname };
    carUseContainerStore.doCancel(parm, () => this.setState({ carLoading: true }, this.query));
  }
  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      const newColumn = column;
      newColumn.render = (text, record, index) => { // 前端元素转义
        const valueSpan = record[`${newColumn.dataIndex}span`] !== undefined ? record[`${newColumn.dataIndex}span`] : record[newColumn.dataIndex];
        if (newColumn.dataIndex == 'carNo') {
          return <div className="wea-url-name" style={{ cursor: 'pointer' }} title={text} onClick={() => { this.carview(record.carid); }} dangerouslySetInnerHTML={{ __html: valueSpan }} />;
        } else if (newColumn.dataIndex == 'aid' && valueSpan.indexOf('href') >= 0) {
          const start = valueSpan.indexOf('(');
          const end = valueSpan.indexOf(')');
          const parm = valueSpan.substring(start + 1, end).replace(/'/g, '').split(',');
          return <div className="wea-url" ><a href="javascript:void(0);" onClick={this.doCancel.bind(this, ...parm)}>{getLabel(16210, '撤销')}</a></div>;
        }
        return <div className="wea-url" dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return columns;
  }
  carview = (id) => {
    this.refs.carview.wrappedInstance.open(id);
  }
  /* 拖曳结束 */
  dragChooseEnd = (dragState, activeCellProps) => {
    const conflict = activeCellProps.some(props => props.conflict);
    this.refs.drag.clear();
    const { startProps, endProps } = dragState;
    const startTime = startProps.startTime;
    const endTime = endProps.endTime;
    const cardid = startProps.room.id;
    let date = this.state.date;
    const month = (date.getMonth() + 1) < 10 ? `0${date.getMonth() + 1}` : (date.getMonth() + 1);
    const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
    date = `${date.getFullYear()}-${month}-${day}`;
    const parms = { startDate: date, startTime, endDate: date, endTime, cardid };
    if (carFlowData && carFlowData.datas) {
      this.openCarCreateFlow(carFlowData, parms);
    } else {
      const { carUseContainerStore } = this.props;
      carUseContainerStore.getCarFlowCreateData(this.openCarCreateFlow.bind(this), parms);
    }
  }

  /* 判断拖拽中的每个块是否激活 */
  checkDragActive = (itemProps, dragState) => {
    let { room, itemPosition } = itemProps,
      { startProps = {} } = dragState,
      startRoom = startProps.room || {};
    if (startRoom.id && room.id == startRoom.id) {
      const { minRow, minColumn, maxRow, maxColumn } = dragState;
      return itemPosition[0] >= minRow && itemPosition[0] <= maxRow && itemPosition[1] >= minColumn && itemPosition[1] <= maxColumn;
    }
    return false;
  }
  openCarCreateFlow = (result, parms) => {
    if (result && result.count) {
      carFlowData = result;
      if (result.count == 0) {
        message.info(getLabel(385845, '没有对应的车辆申请流程可创建'));
      } else if (result.count == 1) {
        const datas = result.datas;
        if (datas.length == 1) {
          const flows = datas[0].flows;
          const workflowid = flows[0].workflowid;
          this.refs.createCarFlow.setParmsAndNewFlow(parms, workflowid);
        }
      } else if (result.count > 1) {
        this.refs.createCarFlow.open(result);
        this.refs.createCarFlow.setParms(parms);
      }
    } else {
      message.error(getLabel(385846, '获取车辆流程失败'));
    }
  }


  // 高级搜索底部按钮定义
  getTabButtonsAd() {
    const { carUseContainerStore } = this.props;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3gx88x@setShowSearchAd`} type="primary" onClick={() => { carUseContainerStore.setShowSearchAd(false); carUseContainerStore.doTableLoading(); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b3bsnb@clearFormFields`} type="ghost" onClick={carUseContainerStore.clearFormFields}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@a7m4kb@setShowSearchAd`} type="ghost" onClick={this.hideSearchAd}>{getLabel(201, '取消')}</Button>),
    ];
  }

  // 右侧操作按钮
  onOperatesClick = (record, index, operate, flag) => {

  }

  /* 立即关闭 */
  toClose = () => {
    this.setState({
      createVisible: false,
    });
  }
  setDialogZIndex = (index) => {
    this.setState({
      dialogZIndex: index,
    });
  }


  /* 获得车辆使用情况的头部 */
  getTableHeaderInfo = (timeType, date, startHour, endHour) => {
    let blockNum = 0,
      tableTitle = '',
      tableHeaders = [];
    const curmoment = moment.isMoment(date) ? date : moment(date);
    if (timeType == 'day') {
      blockNum = endHour - startHour + 1;
      tableTitle = `${curmoment.format(i18n.moment.dateformat.Md3)} ${getLabel(33425, '单位')}:${getLabel(383376, '时')}`;
      for (startHour; startHour <= endHour; startHour++) { tableHeaders.push(startHour); }
    } else if (timeType == 'week') {
      blockNum = 7;
      tableTitle = curmoment.format(i18n.moment.dateformat.y4w2);
      for (var i = 0; i < blockNum; i++) {
        tableHeaders.push(curmoment.day(i).format(i18n.moment.dateformat.Md3));
      }
    } else {
      blockNum = curmoment.daysInMonth();
      tableTitle = `${curmoment.format(i18n.moment.dateformat.yM)} (${blockNum}${getLabel(383378, '天')})`;
      for (var i = 0; i < blockNum; i++) { tableHeaders.push(i); }
    }
    return { blockNum, tableTitle, tableHeaders };
  }

  /* 创建车辆使用情况的每一行td */
  createTdList = (room, blockNum, rowNum) => {
    const { timeType, duration, useMap } = this.state;
    // let tooltipContainer = ReactDOM.findDOMNode(this);
    const tdList = [];
    const useArray = useMap[room.id];
    // 创建冲突的、带有提示的单元格
    const createTooltipTd = function (obj, otherProps) {
      const { content, bgcolor, fontcolor, title } = obj;
      const style = { backgroundColor: bgcolor, color: fontcolor || '#000', textAlign: 'center' };
      const td = (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@gzyn31`} title={createTitle(title)} placement="left" >
          <td style={style} conflict {...otherProps}><div className="car-td-modal" />{content > 1 && content}</td>
        </Tooltip>
      );
      return td;
    };
    if (timeType == 'week' || timeType == 'month') {
      for (let i = 0; i < blockNum; i++) {
        tdList.push(<td><div className="car-td-modal" /></td>);
      }
      if (!useArray || useArray.length == 0) {
        return tdList;
      }
      useArray.forEach((obj) => {
        const tdIdx = timeType == 'week' ? moment(obj.date).day() : moment(obj.date).date() - 1;
        if (tdIdx < 0 || tdIdx >= blockNum) return;
        tdList[tdIdx] = createTooltipTd(obj);
      });
      return tdList;
    }
    return this.createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList);
  }

  /* 创建时间类型为天时的单元格 */
  createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList) {
    let { startHour, endHour } = this.state;
    const useBlockMap = {};// 已被使用的块，数据结构：小时数:{变色的序号：{背景颜色，字体颜色，内容}，...}
    const subNum = duration == 0 ? 1 : Math.floor(60 / duration);// 每小时会被分成几段

    // 生成已被占用的时间段
    useArray && useArray.forEach((obj) => {
      // 时间处理，确认序号
      if (!obj.time) return;
      const time = obj.time.split(':');
      if (time.length != 2) return;
      let hour = parseInt(time[0]),
        minute = parseInt(time[1]);
      const idx = duration > 0 ? Math.floor(minute / duration) : 0;
      // 找到该数据对应的存储位置。
      if (!useBlockMap[hour]) useBlockMap[hour] = {};
      const useHour = useBlockMap[hour];
      useHour[idx] = obj;
    });

    /* 创建每小时内的分隔块、即第二层td的方法 */
    const createSubTd = (hour, idx, rowNum, colNum) => {
      let startMinute = idx * duration,
        endMinute = startMinute + duration - 1;
      let startTime = `${hour > 9 ? hour : `0${hour}`}:${startMinute > 9 ? startMinute : `0${startMinute}`}`,
        endTime = `${hour > 9 ? hour : `0${hour}`}:${endMinute > 9 ? endMinute : `0${endMinute}`}`;
      // 有值则说明已被占用
      if (useBlockMap[hour] && useBlockMap[hour][idx]) {
        return createTooltipTd(useBlockMap[hour][idx], {
          itemPosition: [rowNum, colNum],
          startTime,
          endTime,
          room,
        });
      }
      // 空时段
      return (
        <td itemPosition={[rowNum, colNum]} {...{ startTime, endTime, room }}><div className="car-td-modal" /></td>
      );
    };

    // 生成第一层td列表
    let colNum = 0;
    for (startHour; startHour <= endHour; startHour++) {
      const subTdList = [];
      for (let i = 0; i < subNum; i++) {
        subTdList.push(createSubTd(startHour, i, rowNum, colNum));
        colNum++;
      }
      const td = (
        <td>
          <table className="car-subTable">
            <tr>{subTdList}</tr>
          </table>
        </td>
      );
      tdList.push(td);
    }

    return tdList;
  }

  /* 车辆列表的操作栏 */
  getOperatesClick(record, index, operate, flag) {

  }


  /* 判断拖拽中的每个块是否激活 */
  checkDragActive = (itemProps, dragState) => {
    let { room, itemPosition } = itemProps,
      { startProps = {} } = dragState,
      startRoom = startProps.room || {};
    if (startRoom.id && room.id == startRoom.id) {
      const { minRow, minColumn, maxRow, maxColumn } = dragState;
      return itemPosition[0] >= minRow && itemPosition[0] <= maxRow && itemPosition[1] >= minColumn && itemPosition[1] <= maxColumn;
    }
    return false;
  }

  updateScroll = () => {
    this.refs.tabScroll && this.refs.tabScroll.update();
  }


  changeSubcompany = (nodeObj, callback) => {
    let id = '';
    let name = '';
    if (nodeObj && nodeObj.id && nodeObj.id >= 0) {
      id = nodeObj.id;
      name = nodeObj.name;
    }
    const { carUseContainerStore } = this.props;
    carUseContainerStore.clearFormFields();
    carCondition.subId = id;
    carCondition.subName = name;
    carCondition.bywhat = 4;
    carCondition.carNo = '';
    // let date = new Date();
    // let curmoment = moment.isMoment(date) ? date : moment(date);
    // let currentdate=  curmoment.format("YYYY-MM-DD");
    // carCondition.currentdate = currentdate;
    this.setState({
      subId: id,
      subName: name,
      timeType: 'day',
      // date: new Date(),
      carNo: '',
      callback,
    }, this.query);
  }


  searchList = () => {
    const { carUseContainerStore } = this.props;
    const param = this.getQueryParams();
    const currentdate = param.currentdate;
    const bywhat = param.bywhat;
    let id = '';
    let name = '';
    if (param.subId) {
      id = param.subId;
      name = param.subName;
    }
    const carid = param.carId;
    const carNo = param.carNo;
    carUseContainerStore.appendFormFields({
      bywhat: `${bywhat}`,
      currentdate,
      carId: `${carid}`,
      carNo,
      subId: {
        value: id,
        valueSpan: name,
        valueObj: [
          {
            id,
            name,
          },
        ],
      },
    });
    carUseContainerStore.setShowSearchAd(false);
    carUseContainerStore.doTableLoading();
  }
}

/* 获得时间类型的DOM */
const getTimeTypeSpan = function (timeType, curType, func) {
  let timeTypeLabel;
  switch (timeType) {
    case 'day': timeTypeLabel = getLabel(390, '日'); break;
    case 'week': timeTypeLabel = getLabel(1926, '周'); break;
    case 'month': timeTypeLabel = getLabel(6076, '月'); break;
    default: timeType = 'month'; timeTypeLabel = '月'; break;
  }
  return (
    <span className={curType == timeType ? 'cur' : ''} onClick={func.bind(this, timeType)}>{timeTypeLabel}</span>
  );
};
/* 创建车辆的提示信息，以及其它提示说明 */
const createRoomTitle = function (titleList) {
  let tipArr = [];
  if (Array.isArray(titleList) && titleList.length > 0) {
    tipArr = tipArr.concat(titleList.map(tip => <div>{tip}</div>));
  }
  return <div style={{ width: 210 }}>{tipArr}</div>;
};

/* 创建车辆的提示信息 */
const createTitle = function (titleList) {
  if (Array.isArray(titleList) && titleList.length > 0) {
    return (
      <div className="wea-roomplan-titletip">
        {titleList.map((meet, idx) => (
          <div>
            {meet.map(tip => <div>{tip}</div>)}
            {idx + 1 < titleList.length && <div className="line" />}
          </div>
        ))}
      </div>
    );
  }
  return undefined;
};

const searchPageTable = sessionKey => (dispatch) => {
  dispatch(WeaTableAction.getDatas(sessionKey, 1));
};

CarUseContainer.defaultProps = {
  canCreate: true,
};
CarUseContainer.propTypes = {
  subId: React.PropTypes.string, // 分部id
  subName: React.PropTypes.string, // 分部名称
  canCreate: React.PropTypes.bool, // 是否可在周期为天时新建
};

// const RoomPlanContainerConnect =  connect(
//     mapStateToProps,
//     mapDispatchToProps,
//     undefined,
//     {withRef: true}
// )(
//     CarUseContainer
// );

// 组件检错机制
class MyErrorHandler extends Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== '';
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@hpwgn2`} msg={hasErrorMsg ? this.props.error : '对不起，该页面异常，请联系管理员！'} />
    );
  }
}

export default CarUseContainer;

